package com.design.testdemo.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.design.testdemo.R;
import com.design.testdemo.adapter.WeiAdapter;
import com.design.testdemo.adapter.YiAdapter;
import com.inuker.bluetooth.library.BluetoothClient;
import com.inuker.bluetooth.library.Code;
import com.inuker.bluetooth.library.connect.options.BleConnectOptions;
import com.inuker.bluetooth.library.connect.response.BleConnectResponse;
import com.inuker.bluetooth.library.connect.response.BleNotifyResponse;
import com.inuker.bluetooth.library.connect.response.BleWriteResponse;
import com.inuker.bluetooth.library.model.BleGattProfile;
import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.scan)
    Button mScan;
    @BindView(R.id.close)
    Button mClose;
    @BindView(R.id.left)
    Button mLeft;
    @BindView(R.id.shake)
    Button mShake;
    @BindView(R.id.right)
    Button mRight;
    @BindView(R.id.dianliang)
    TextView mDianliang;
    @BindView(R.id.weilianjie)
    ListView mWeilianjie;
    @BindView(R.id.yilianjie)
    ListView mYilianjie;
    @BindView(R.id.activity_main)
    LinearLayout mActivityMain;
    private BluetoothClient mClient;

    private boolean isConnect;
    private String mac;
    private ProgressDialog mDialog;
    private WeiAdapter mWeiAdapter;
    private YiAdapter mYiAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);


        getStatus();

        mClient = new BluetoothClient(this);

        mDialog = new ProgressDialog(this);

        mWeiAdapter = new WeiAdapter(this);
        mWeilianjie.setAdapter(mWeiAdapter);

        mYiAdapter = new YiAdapter(this);
        mYilianjie.setAdapter(mYiAdapter);

        mWeilianjie.setOnItemClickListener(mWeiOnitem);

        if (!mClient.isBluetoothOpened()) {
            mClient.openBluetooth();
        }
    }

    private void getStatus() {
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        Log.e("WangJ", "状态栏-方法1:" + statusBarHeight1);
    }

    private boolean b;

    @OnClick({R.id.scan, R.id.close, R.id.left, R.id.shake, R.id.right, R.id.stop_shake})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.scan:
                if (isConnect) {
                    return;
                }
                scan();
                break;
            case R.id.close:
                if (isConnect) {
                    mTvTitle.setText("连接失败");
                    isConnect = false;
                    mClient.disconnect(mac);
                }
                break;
            case R.id.left:
                if (!isConnect) {
                    return;
                }

                byte[] left = {(byte) 0xbb, (byte) 0x67, (byte) 0x00, (byte) 0x00, (byte) 0xe4, (byte) 0x82};
                writeData(left);

                break;
            case R.id.shake:

                byte[] shake = {(byte) 0xbb, (byte) 0x67, (byte) 0x00, (byte) 0x01, (byte) 0xe4, (byte) 0x82};
                writeData(shake);

                break;
            case R.id.right:

                if (!isConnect) {
                    return;
                }

                byte[] right = {(byte) 0xbb, (byte) 0x67, (byte) 0x00, (byte) 0x02, (byte) 0xe4, (byte) 0x82};
                writeData(right);
                break;
            case R.id.stop_shake:

                byte[] stop_shake = {(byte) 0xbb, (byte) 0x83, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x82};
                writeData(stop_shake);

                break;
        }
    }

    private List<String> mStringList = new ArrayList<>();

    private void scan() {

        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(4000, 3)   // 先扫BLE设备3次，每次3s
                .build();


        mClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                mDialog.show();
            }

            @Override
            public void onDeviceFounded(SearchResult device) {

                String name = device.getName();

                if (name == null) {
                    return;
                }
                if (name.contains("H001")) {
                    if (!mStringList.contains(name)) {
                        mWeiAdapter.setData(device);
                    }
                }
            }

            @Override
            public void onSearchStopped() {
                mDialog.dismiss();
            }

            @Override
            public void onSearchCanceled() {

            }
        });
    }


    //=============================

    private AdapterView.OnItemClickListener mWeiOnitem = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final SearchResult item = mWeiAdapter.getItem(position);

            mac = item.getAddress();

            mClient.connect(mac, options, new BleConnectResponse() {
                @Override
                public void onResponse(int code, BleGattProfile data) {
                    if (code == Code.REQUEST_SUCCESS) {
                        isConnect = true;
                        //连接成功

                        mStringList.add(item.getName());
                        mYiAdapter.setData(item);

                        mTvTitle.setText("连接成功");

                        notiy();
                    } else if (code == Code.REQUEST_CANCELED) {
                        mTvTitle.setText("连接失败");
                        isConnect = false;
                        Toast.makeText(MainActivity.this, "蓝牙连接失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    };

    BleConnectOptions options = new BleConnectOptions.Builder()
            .setConnectRetry(3)   // 连接如果失败重试3次
            .setConnectTimeout(10000)   // 连接超时30s
            .build();


    //=============================


    public UUID getUUid(String uuid) {

        return UUID.fromString(uuid);
    }

    private String service = "000056ff-0000-1000-8000-00805f9b34fb";
    private String writeService = "000033f2-0000-1000-8000-00805f9b34fb";
    private String notiService = "000033f1-0000-1000-8000-00805f9b34fb";

    private void writeData(byte[] data) {

        mClient.write(mac, getUUid(service), getUUid(writeService), data, new BleWriteResponse() {
            @Override
            public void onResponse(int code) {
                if (code == Code.REQUEST_SUCCESS) {
                    Toast.makeText(MainActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


    private void notiy() {
        mClient.notify(mac, getUUid(service), getUUid(notiService), new BleNotifyResponse() {
            @Override
            public void onNotify(UUID service, UUID character, byte[] value) {
                byte b = value[2];

                mDianliang.setText("电量: " + b);
            }

            @Override
            public void onResponse(int code) {
                if (code == Code.REQUEST_SUCCESS) {

                }
            }
        });
    }

}
